import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:kkhousekeep/page/home/convenient/order/order_transfer_controller.dart';
import 'package:kkhousekeep/tools/toast_util.dart';

import '../../../../widget/bottom_confirm_bar.dart';
import '../../../../widget/custom_app_bar.dart';
import '../../../../widget/custom_picker.dart';
import '../../../../widget/custom_table.dart';

class OrderTransferPage extends StatelessWidget {
  const OrderTransferPage({super.key});

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () => FocusManager.instance.primaryFocus?.unfocus(),
      child: GetBuilder<OrderTransferController>(
        init: OrderTransferController(),
        builder: (controller) => Scaffold(
          backgroundColor: const Color(0xFFf4f5f6),
          appBar: CustomAppBar("转单"),
          body: SafeArea(
            left: false,
            right: false,
            child: Obx(
                  () => Column(
                children: [
                  Expanded(
                    child: Container(
                      margin: EdgeInsets.only(top: 16.h, bottom: 14.h),
                      child: SingleChildScrollView(
                        child: Container(
                          color:Colors.white,
                          padding: EdgeInsets.only(
                              bottom: MediaQuery.of(context).viewInsets.bottom),
                          child: Column(
                            mainAxisSize: MainAxisSize.min,
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              _buildDetail(context, controller),
                              Text(
                                controller.fatalDesc.value,
                                textAlign: TextAlign.left,
                                style: TextStyle(
                                    fontSize: 32.sp,
                                    color: const Color(0xFF333333)),
                              ).marginOnly(left: 32.w, right: 32.w, bottom: 20.h),
                              buildDescriptionPicture(),
                              _buildDetail2(context, controller),
                              TextField(
                                keyboardType: TextInputType.multiline,
                                maxLines: 5,
                                minLines: 1,
                                maxLength: 50,
                                controller: controller.remarkTextEditController,
                                decoration: InputDecoration(
                                  hintText: '请输入备注',
                                  contentPadding: const EdgeInsets.symmetric(
                                      horizontal: 0, vertical: 0),
                                  isDense: true,
                                  counterStyle: TextStyle(
                                      color:
                                      (controller.remark.value.length == 50)
                                          ? const Color(0xFFDD5045)
                                          : const Color(0xFFCECECE),
                                      fontSize: 32.sp),
                                  border: InputBorder.none,
                                  hintStyle: TextStyle(
                                      color: const Color(0xFFCECECE),
                                      fontSize: 32.sp),
                                ),
                              ).marginOnly(left: 32.w, right: 32.w, bottom: 30.h),
                              Padding(padding: MediaQuery.of(context).viewInsets),
                            ],
                          ),
                        ),
                      ),
                    ),
                  ),
                  buildBottomSheet(),
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }

  Widget _buildDetail(
      BuildContext buildContext, OrderTransferController controller) {
    return CustomTable(
      children: [
        TableRow(children: [
          CustomTable.buildFormTitle("工单编号"),
          CustomTable.buildFormContent(controller.woSn.value)
              .marginOnly(left: 60.w),
        ]),
        TableRow(children: [
          CustomTable.buildFormTitle("故障类型"),
          CustomTable.buildFormContent(controller.fatalType.value)
              .marginOnly(left: 60.w),
        ]),
        TableRow(children: [
          CustomTable.buildFormTitle("报修地址"),
          CustomTable.buildFormContent(controller.address.value)
              .marginOnly(left: 60.w),
        ]),
        TableRow(children: [
          CustomTable.buildFormTitle("故障描述"),
          Container(),
        ]),
      ],
    );
  }

  Widget _buildDetail2(
      BuildContext buildContext, OrderTransferController controller) {
    return CustomTable(
      children: [
        TableRow(
          children: [
            CustomTable.buildFormTitle("接单部门", isRequired: true),
            Padding(
              padding: EdgeInsets.only(left: 60.w, right: 32.w),
              child: CustomTable.buildSelection(
                  text: controller.department.value,
                  onTap: () {
                    controller.getDepartmentList().then(
                          (value) => _showDepartmentPicker((index) => {
                                controller.selectDepartment(
                                    controller.departments[index])
                              }),
                        );
                  }),
            ),
          ],
        ),
        TableRow(
          children: [
            CustomTable.buildFormTitle("接单人员"),
            Padding(
              padding: EdgeInsets.only(left: 60.w, right: 32.w),
              child: CustomTable.buildSelection(
                  text: controller.staff.value,
                  onTap: () {
                    if (controller.selectedDepartment == null) {
                      ToastUtils.showToast(tip: "请先选择部门");
                      return;
                    }
                    controller.getStaffList().then(
                          (value) => _showStaffPicker((index) => {
                                controller.selectStaff(controller.staffs[index])
                              }),
                        );
                  }),
            ),
          ],
        ),
        TableRow(
          children: [
            CustomTable.buildFormTitle("备注"),
            Container(),
          ],
        ),
      ],
    );
  }

  buildDescriptionPicture() {
    OrderTransferController controller = Get.find();
    return GridView.builder(
      primary: false,
      scrollDirection: Axis.vertical,
      shrinkWrap: true,
      padding: EdgeInsets.only(top: 12.h, bottom: 40.h),
      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: 3,
        mainAxisSpacing: 24.h,
        crossAxisSpacing: 24.w,
      ),
      itemCount: controller.descImg.length,
      itemBuilder: (context, index) {
        return buildDescriptionPictureItem(controller.descImg[index]);
      },
    ).marginSymmetric(horizontal: 32.w);
  }

  buildDescriptionPictureItem(String imgUrl) {
    OrderTransferController controller = Get.find();
    return InkWell(
      child: CachedNetworkImage(
        imageUrl: imgUrl,
        imageBuilder: (context, imageProvider) => Container(
          decoration: BoxDecoration(
            borderRadius: BorderRadius.all(
              Radius.circular(6.r),
            ),
            image: DecorationImage(
              fit: BoxFit.cover,
              image: imageProvider,
            ),
          ),
        ),
        placeholder: (context, url) => Container(
          color: Colors.grey,
        ),
        errorWidget: (context, url, error) => const Icon(Icons.error),
      ),
      onTap: () {
        if (imgUrl.isNotEmpty) {
          controller.clickImageItem(imgUrl);
        }
      },
    );
  }

  buildBottomSheet() {
    OrderTransferController controller = Get.find();
    return BottomConfirmBar(
      leftText: "取消",
      onTapLeft: () {
        Get.back();
      },
      rightText: "提交",
      onTapRight: () {
        controller.orderTransfer();
      },
    );
  }

  void _showDepartmentPicker(confirmCallback, {String? value}) {
    OrderTransferController controller = Get.find();
    var index = 0;
    if (value != null) {
      index = controller.departmentsStringList.indexOf(value);
    }
    Get.bottomSheet(
      CustomPick(
        index: index,
        pickList: controller.departmentsStringList,
        confirmCallBack: confirmCallback,
        cancelCallBack: (index) => {Get.back()},
      ),
    );
  }

  void _showStaffPicker(confirmCallback, {String? value}) {
    OrderTransferController controller = Get.find();
    var index = 0;
    if (value != null) {
      index = controller.staffsStringList.indexOf(value);
    }
    Get.bottomSheet(
      CustomPick(
        index: index,
        pickList: controller.staffsStringList,
        confirmCallBack: confirmCallback,
        cancelCallBack: (index) => {Get.back()},
      ),
    );
  }
}
